#include<cstdlib>
#include<arpa/inet.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<iostream>
#include<netinet/in.h>
#include<string.h>
#include<unistd.h>

void Usage(std::string s)
{
  std::cout<<"Usage "<<"\n\t"<<s<<"desc_ip desc_port"<<std::endl;
}
//客户端
int main(int argv,char * argc[])
{
  //通过命令行参数传递服务器ip,和端口号
  if(argv!=3)
  {
    Usage(argc[0]);
  }
  int sock=socket(AF_INET,SOCK_DGRAM,0);
  if(sock<0)
  {
    std::cerr<<"socket error "<<std::endl;
  }
  //客户端不需要手动bind,操作系统会绑定相应的端口号
  
  //访问服务端
  struct sockaddr_in desc;
  desc.sin_family=AF_INET;
  desc.sin_port=htons(atoi(argc[2]));
  desc.sin_addr.s_addr=inet_addr(argc[1]);                      //命令行输入一般都是点分十进制

  char buffer[1024];
  buffer[0]=0;
  while(1)
  {
    //从标准输入中读取数据
    std::cout<<"请输入命令:";
    fflush(stdout);
    ssize_t s=read(0,buffer,sizeof(buffer));
    buffer[s-1]=0;

    if(sendto(sock,buffer,sizeof(buffer),0,(struct sockaddr*)&desc,sizeof(desc))<0)
    {
      std::cerr<<"sendto error"<<std::endl;
      continue;
    }
    struct sockaddr_in peer;
    socklen_t len=sizeof(peer);
    ssize_t m=recvfrom(sock,buffer,sizeof(buffer),0,(struct sockaddr*)&peer,&len);
    if(s>0)
    {
      buffer[m]=0;
      std::cout<<buffer<<std::endl;
    }
  }
  return 0;
}
